package RiskAlert;

import java.util.Arrays;


/**
 * 求逆矩阵
 */

public class test{

	private double[][] matrix;//原始矩阵右侧加以单位矩阵
	private double[][] inversematrix;//逆矩阵

	public test(double[][] originmatrix){
		
		int row=originmatrix.length;
		int column=originmatrix.length*2;

		this.matrix=new double[row][column];

		for(int i=0;i<row;i++){
			for(int j=0;j<row;j++)
			this.matrix[i][j]=originmatrix[i][j];
		}

		for(int i=0;i<row;i++){
			for(int j=0;j<column;j++)
				System.out.print(this.matrix[i][j]+" ");
			System.out.println();
		}

		int i=originmatrix.length;
		int j=originmatrix.length;

		System.out.println("Print out the array first.");
		for(int x=0;x<i;x++)
		{
			for(int y=0;y<j;y++)
			{
				System.out.print(originmatrix[x][y]+"  ");
			}
			System.out.println();
		}
		System.out.println("\nThen Try to change it.Use identity matrix.");
		//add the identity array at the end 
		for(int k=0;k<i;k++)
		{
			for(int t=j;t<j*2;t++)
			{
				if((t-k)==j)
				{
					matrix[k][t]=1.0;
				}
				else
				{
					matrix[k][t]=0;
				}
			}
		}
		for(int x=0;x<i;x++)
		{
			for(int y=0;y<j*2;y++)
			{
				System.out.print(matrix[x][y]+"  ");
			}
			System.out.println();
		}
		//get the change of the array
		for(int k=0;k<i;k++)
		{
			if(matrix[k][k]!=1)
			{
				double bs = matrix[k][k];
				matrix[k][k]=1;
				for(int p=k;p<j*2;p++)
				{
					matrix[k][p]/=bs;
					//      System.out.println("Vp["+k+","+p+"]="+Vp[k][p]);
				}

			}

			for(int q=0;q<i;q++)
			{
				if(q!=k)
				{
					double bs = matrix[q][k];
					for(int p=0;p<j*2;p++)
					{
						//       System.out.println(bs);
						matrix[q][p]-=bs*matrix[k][p];
						//       System.out.println("Vp["+q+","+p+"]="+Vp[q][p]);
					}
				}
				else
				{
					continue;
				}
			}
		}
		//print out the result of the change
		System.out.println("\nThe result is:");
		for(int x=0;x<i;x++)
		{
			for(int y=j;y<j*2;y++)
			{
				System.out.print(matrix[x][y]+"  ");
			}
			System.out.println();
		}
	}

	public static void main(String args[])
	{
		double[][] a=new double[3][3];
		  a[0][0] = 1;
		  a[0][1] = 2;
		  a[0][2] = 3;
		  a[1][0] = 2;
		  a[1][1] = 2;
		  a[1][2] = 1;
		  a[2][0] = 3;
		  a[2][1] = 4;
		  a[2][2] = 3;
		
		test cm = new test(a);
	} 

}